import json
from django.contrib.auth import login
from django.http import JsonResponse
from django.shortcuts import render
# Create your views here.
from QQLoginTool.QQtool import OAuthQQ
from django.views import View
from apps.users.models import User
from meiduo_mall import settings
from apps.oauth.models import OAuthQQUser
from apps.oauth.utils import generic_openid, check_access_token


class QQLoginURLView(View):

    def get(self, request):
        qq = OAuthQQ(client_id=settings.QQ_CLIENT_ID,
                     client_secret=settings.QQ_CLIENT_SECRET,
                     redirect_uri=settings.QQ_REDIRECT_URI,
                     state='xxx')
        qq_login_url = qq.get_qq_url()
        return JsonResponse({'code': 0,
                             'errmsg': 'OK',
                             'login_url': qq_login_url})


class OauthQQView(View):

    def get(self, request):
        code = request.GET.get('code')
        if code is None:
            return JsonResponse({'code': 400, 'errmsg': '参数不全'})
        qq = OAuthQQ(client_id=settings.QQ_CLIENT_ID,
                     client_secret=settings.QQ_CLIENT_SECRET,
                     redirect_uri=settings.QQ_REDIRECT_URI,
                     state='xxx')
        token = qq.get_access_token(code)
        openid = qq.get_open_id(token)
        try:
            qquser = OAuthQQUser.objects.get(openid=openid)
        except OAuthQQUser.DoesNotExist:
            # 不存在，需要绑定
            access_token = generic_openid(openid)
            response = JsonResponse({'code': 400, 'access_token': access_token})
            return response

        else:
            # 存在，直接登录
            login(request, qquser.user)
            response = JsonResponse({'code': 0, 'errmsg': 'OK'})
            response.set_cookie('username', qquser.user.username)
            return response

    def post(self, request):
        data = json.loads(request.body.decode())
        mobile = data.get('mobile')
        password = data.get('password')
        sms_code = data.get('sms_code')
        access_token = data.get('access_token')
        openid = check_access_token(access_token)
        if openid is None:
            return JsonResponse({'code': 400, 'errmsg': '参数缺失'})
        # 对数据进行验证
        # TODO
        try:
            user = User.objects.get(mobile=mobile)
        except User.DoesNotExist:
            # 不存在用户就创建用户
            user = User.objects.create_user(username=mobile, mobile=mobile, password=password)
        else:
            # 存在就直接进行绑定
            if not user.check_password(password):
                return JsonResponse({'code': 400, 'errmsg': '账号或者密码错误'})
        OAuthQQUser.objects.create(user=user, openid=openid)
        login(request, user)
        response = JsonResponse({'code': 0, 'errmsg': 'OK'})
        response.set_cookie('username', user.username)
        return response


